package com.example.springdemo0921.springboot;

import lombok.Data;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * Spring原生增强器
 * BeanFactoryPostProcessor(xxx系列) : bean工厂增强器,工厂完毕之后可以为所欲为
 * BeanNameAware(xxx系列) : aware属性增强器,初始化前，先设置通用属性
 * BeanPostProcessor(xxx系列) : bean增强器, bean初始化前、后执行的方法
 * @author kusej
 * Create at 2022-09-20 15:56
 **/

@Data
@Component
public class SpringPostProcessorTest implements BeanFactoryPostProcessor, BeanNameAware, EnvironmentAware, BeanPostProcessor, InitializingBean {
    @PostConstruct
    public void init(){
        System.out.println("SpringPostProcessorTest初始化完成： "+this.toString());
    }
    String beanName;
    Environment env;
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        BeanDefinition productRateConfig = beanFactory.getBeanDefinition("productRateConfig");
        productRateConfig.getPropertyValues().add("invalidWordSep","zhangsan"); // 修改属性值
     }

    @Override
    public void setBeanName(String name) {
        this.beanName = name;
    }


    @Override
    public void setEnvironment(Environment environment) {
        this.env = environment;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (beanName.equalsIgnoreCase("productRateConfig")){
            ProductRateConfig temp = (ProductRateConfig)bean;
            temp.setSensitiveWordSep("lisi");
        }
        return bean;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("afterPropertiesSet 初始化： "+this.toString());
    }
}
